package com.fyzk.activity.user.xiangxi;

import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Message;
import android.text.Html;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;
import com.fyzk.base.BaseActivity;
import com.fyzk.activity.chongzhi.RechargeActivity;
import com.fyzk.activity.user.jczq_sp.JCZQ_SPActivity;
import com.fyzk.bean.AccountMoneyResponse;
import com.fyzk.bean.ZCOrderInfo;
import com.fyzk.betcode.AppLotteryCodeListManager;
import com.fyzk.data.AppLotteryInfos;
import com.fyzk.dialog.DJ_ProgressDialog;
import com.tyjc.lottery.R;
import com.fyzk.net.Commands;
import com.fyzk.net.PublicMethod;
import com.fyzk.raceview.RaceFactory;
import com.fyzk.utils.HandlerTypeUtils;
import com.fyzk.utils.IntentParamUtils;
import com.fyzk.utils.LotteryIDUtils;
import com.fyzk.view.TopTitleView;

import org.json.JSONException;
import org.json.JSONObject;
import org.xutils.view.annotation.ContentView;
import org.xutils.view.annotation.ViewInject;

import java.util.List;

import http.Common.CommandUtil;
import http.Common.SchemaDef;
import http.DataUtil.text.TextUtil;
import http.StringResultBean;

/**
 * 传统足彩订单详情
 */
@ContentView(R.layout.orderdetail)
public class OldFootballOrderDetailActivity extends BaseActivity {

    private String id;

    private TopTitleView xiangxi_title_rl;
    private TextView tv_caiZhong;
    private TextView xiangxi_tiket;
    private TextView tv_money;
    private TextView tv_couponMoney;
    private LinearLayout ll_couponMoney;
    private TextView tv_beiShu;
    private TextView tv_id;
    private TextView tv_phase;
    private TextView tv_time;
    private TextView tv_state;
    private TextView tv_prizeMoney;

    protected LinearLayout ll_content;
    protected LinearLayout ll_prize;

    private TextView tv_jiXu;
    @ViewInject(R.id.xiangxi_bettype)
    private TextView xiangxi_bettype;

    private String wanFaId;
    private String wanFa;
    private String guoGuan;
    private String touZhuContent;
    protected TextView jczq_sp_tv;

    private double leftMoney;   // 用户彩金
    private int orderMoney;     // 订单彩金(整数，用int)
    private long lowMoney;       // 待支付差额(支付必须是整数)


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        info();
        id = getIntent().getStringExtra(IntentParamUtils.BETDETAILID);
        DJ_ProgressDialog.show(getContext(), true, true);
//		requestData(SchemaDef.COMMON_BET_RECORD_DETAIL);
        getOrderInfo();
        requestLeftMoney();
    }

    private void requestLeftMoney() {
        httpPostJson(CommandUtil.ACCOUNT_MONEY, Commands.ACCOUNT_MONEY, null, true);
    }

    private void getOrderInfo() {
        JSONObject json = new JSONObject();
        try {
            json.put("orderid", id);
        } catch (JSONException e) {
            e.printStackTrace();
        }
        httpPostJson(CommandUtil.COMMON_BET_RECORD_DETAIL, Commands.ORDERINFO, json, true);

    }

    ZCOrderInfo info;

    @Override
    protected void onSuccess(int requestCode, StringResultBean resultBean, String result) {
        super.onSuccess(requestCode, resultBean, result);
        switch (requestCode) {
            case CommandUtil.ACCOUNT_MONEY:
                AccountMoneyResponse accountMoneyResponse = JSON.parseObject(resultBean.getData(),
                        AccountMoneyResponse.class);
                leftMoney = Double.parseDouble(PublicMethod.formatBalance(accountMoneyResponse.getBalance()));
                break;
            case CommandUtil.COMMON_BET_RECORD_DETAIL:
                perseOrder(resultBean);
                fuZhi();

                break;
        }
    }

//	CommonRecordDetailResponseData responseObj;

    protected void request(int schemaDef) {
        switch (schemaDef) {
            case SchemaDef.COMMON_BET_RECORD_DETAIL:
                getXiangXi(id, schemaDef);
                break;
            default:
                break;
        }
    }

    protected void parserMessage(Message msg) {
        DJ_ProgressDialog.dissmiss();
        switch (msg.what) {
            case HandlerTypeUtils.ZY_HANDLER_TYPE_LOAD_RECORDDETAIL_SUCCESS:
                if (getLotteryId().equals("" + LotteryIDUtils.JZHH_LOTTERY_ID_INT) || getLotteryId
                        ().equals("" + LotteryIDUtils.JZBF_LOTTERY_ID_INT)
                        || getLotteryId().equals("" + LotteryIDUtils.JZBQC_LOTTERY_ID_INT) ||
                        getLotteryId().equals("" + LotteryIDUtils.JZHH_LOTTERY_ID_INT)
                        || getLotteryId().equals("" + LotteryIDUtils.JZRFSPF_LOTTERY_ID_INT) ||
                        getLotteryId().equals("" + LotteryIDUtils.JZSPF_LOTTERY_ID_INT)
                        || getLotteryId().equals("" + LotteryIDUtils.JZZJQ_LOTTERY_ID_INT)) {
                    jczq_sp_tv.setVisibility(View.VISIBLE);
                } else {
                    jczq_sp_tv.setVisibility(View.INVISIBLE);
                }
                tv_jiXu.setText("投注" + AppLotteryInfos.getLotteryName(getLotteryId()));
                fuZhi();
                addAdpter();
                break;
            case HandlerTypeUtils.ZY_HANDLER_TYPE_LOAD_DATA_FAIL:
                Toast.makeText(this, "联网失败", Toast.LENGTH_LONG).show();
                break;
            default:
                break;
        }
    }

    /**
     * 得到内容串
     *
     * @return
     */
    public String getContent() {
//		if (responseObj == null) {
        return "";
//		}
//		return responseObj.content;
    }

    /**
     * 得到开奖号码
     *
     * @return
     */
    public String getPrize() {
//		if (responseObj == null) {
        return "";
//		}
//		return responseObj.prizeNum;
    }

    /**
     * 数字彩添加adapter
     */
    public void addAdpter() {

    }

    public String getLotteryId() {
        return info.getLotteryType() + "";
    }

    /**
     * 初始化控件
     */
    private void info() {

        xiangxi_title_rl = (TopTitleView) findViewById(R.id.order_topview);
        xiangxi_title_rl.setOnTitleClickListener(this);

        tv_caiZhong = (TextView) findViewById(R.id.order_lotteryName);
        xiangxi_tiket = (TextView) findViewById(R.id.xiangxi_tiket);
        tv_money = (TextView) findViewById(R.id.xiangxi_fanganmoney);
        tv_couponMoney = (TextView) findViewById(R.id.xiangxi_couponmoney);
        ll_couponMoney = (LinearLayout) findViewById(R.id.xiangxi_coupon_ll);
        tv_beiShu = (TextView) findViewById(R.id.xiangxi_beishu);
        tv_id = (TextView) findViewById(R.id.xiangxi_fanganid);
        tv_phase = (TextView) findViewById(R.id.xiangxi_phase);
        tv_time = (TextView) findViewById(R.id.xiangxi_time);
        tv_state = (TextView) findViewById(R.id.xiangxi_state);
        tv_prizeMoney = (TextView) findViewById(R.id.xiangxi_zjmoney);

        ll_content = (LinearLayout) findViewById(R.id.xiangxi_content);
        ll_prize = (LinearLayout) findViewById(R.id.xiangxi_ll_prizeinfor);


        tv_jiXu = (TextView) findViewById(R.id.order_txt_continue);

        jczq_sp_tv = (TextView) findViewById(R.id.xiangxi_jczqsp_tv);
        jczq_sp_tv.setOnClickListener(new ZCXX_onClick());

        tv_jiXu.setOnClickListener(new ZCXX_onClick());

    }

    /**
     * 获取订单详细信息
     *
     * @param id
     */
    private void getXiangXi(String id, int schemaDef) {
//		ProtocalEngine engine = new ProtocalEngine(getContext());
//		CommonRecordDetailRequestData requestData = new CommonRecordDetailRequestData();
//		requestData.orderid = id;
//		engine.request(this, schemaDef, requestData);
    }

    /**
     * 给控件赋值
     */
    public void fuZhi() {
        if (!TextUtil.isEmpty(info.getIsRecharge()) && info.getIsRecharge().equals("1")) {
            xiangxi_title_rl.setRightVisible(View.VISIBLE);
            xiangxi_title_rl.setRightTxt("支付");
        } else {
            xiangxi_title_rl.setRightVisible(View.INVISIBLE);
        }
        orderMoney = info.getAmount() / 100;
        tv_caiZhong.setText(info.getLotteryTypeName());
        tv_money.setText("" + PublicMethod.formatMoney(info.getAmount()));
        if (info.getPreferentialAmount() > 0) {
            tv_couponMoney.setText("" + PublicMethod.formatMoney(info.getPreferentialAmount()));
        } else {
            ll_couponMoney.setVisibility(View.GONE);
        }
        tv_beiShu.setText("" + info.getMultiple());
        tv_id.setText("" + id);
        tv_phase.setText("" + info.getPhase() + "期");
        tv_time.setText("" + info.getReceiveTime());
        tv_state.setText("" + info.getOrderResultStatusName());
        xiangxi_tiket.setText("" + info.getOrderStatusName());

        if (info.getAddprize() > 0) {
            tv_prizeMoney.setText(Html.fromHtml(String.valueOf(
                    PublicMethod.formatMoney(info.getPrize() * 1.0)) + "<font color='#666666'>(加奖</font>"
                    + PublicMethod.formatMoney(info.getAddprize() * 1.0) + "<font color='#666666'>)</font>"));
        } else {
            tv_prizeMoney.setText(String.valueOf(
                    PublicMethod.formatMoney(info.getPrize() * 1.0)));
        }

        xiangxi_bettype.setText(info.getBettype());

        View view = View.inflate(this, R.layout.layout_zcbetcode, null);
        TextView playName = (TextView) view.findViewById(R.id.playName);
        playName.setText("玩法:" + info.getDetail().getPlayName());
        ListView ls = (ListView) view.findViewById(R.id.jc_betcode);
        List<ZCOrderInfo.DetailBean.RaceBetcodeBean> raceBetcodeBeens = info.getDetail().getRaceBetcode();

        if (info.getWincode() != null && info.getWincode().toString().contains(",")) {
            winCodes = info.getWincode().toString().split(",");
        }

        BetCodeAdapter betCodeAdapter = new BetCodeAdapter(raceBetcodeBeens);
        ls.setAdapter(betCodeAdapter);
        ll_content.addView(view);

    }

    String[] winCodes;

    class BetCodeAdapter extends BaseAdapter {

        private List<ZCOrderInfo.DetailBean.RaceBetcodeBean> raceBetcodeBeens;

        BetCodeAdapter(List<ZCOrderInfo.DetailBean.RaceBetcodeBean> raceBetcodeBeens) {
            this.raceBetcodeBeens = raceBetcodeBeens;
        }

        @Override
        public int getCount() {
            return raceBetcodeBeens.size();
        }

        @Override
        public ZCOrderInfo.DetailBean.RaceBetcodeBean getItem(int position) {
            return raceBetcodeBeens.get(position);
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            ViewHolder holder = null;
            if (convertView == null) {
                convertView = View.inflate(OldFootballOrderDetailActivity.this, R.layout
                        .layout_zcbetcode_item, null);
                holder = new ViewHolder();
                holder.teamname = (TextView) convertView.findViewById(R.id.team);
                holder.betcode = (TextView) convertView.findViewById(R.id.betcode);
                holder.id = (TextView) convertView.findViewById(R.id.team_id);
                convertView.setTag(holder);
            } else {
                holder = (ViewHolder) convertView.getTag();
            }

            ZCOrderInfo.DetailBean.RaceBetcodeBean raceBetcodeBean = raceBetcodeBeens.get(position);

            int id = raceBetcodeBean.getMatchNum();
            holder.id.setText(id + "");
            String team = raceBetcodeBean.getHomeTeam() + " VS " + raceBetcodeBean
                    .getAwayTeam();
            holder.teamname.setText(team);
            if (getLotteryId().equals(LotteryIDUtils.ZCJQC_LOTTERY_ID_INT + "")) {
                holder.betcode.setText("主:" + raceBetcodeBean.getHbetcode() + "\n" + "客:" + raceBetcodeBean.getAbetcode());
            } else if (getLotteryId().equals(LotteryIDUtils.ZCBQC_LOTTERY_ID_INT + "")) {
                holder.betcode.setText("半:" + raceBetcodeBean.getBbetcode() + "\n" + "全:" + raceBetcodeBean.getQbetcode());
            } else {
                if (winCodes != null && raceBetcodeBean.getBetcode().equals(winCodes[id - 1])) {
                    holder.betcode.setTextColor(Color.RED);
                } else {
                    holder.betcode.setTextColor(getResources().getColor(R.color.color_333333));
                }
                holder.betcode.setText(raceBetcodeBean.getBetcode());
            }

            return convertView;
        }


        class ViewHolder {
            TextView id;
            TextView teamname;
            TextView betcode;

        }
    }


    /**
     * 拆分投注内容
     */
    private void splitContent(String content) {
        if (content == null || content.equals("")) {
            return;
        }
        String front = "";
        if (content.contains("-")) {
            front = content.split("-")[0];
        }

        if (front != null && front.length() >= 9) {
            wanFaId = front.substring(0, 4);
            wanFa = front.substring(4, 5);
            guoGuan = front.substring(5, front.length());
        } else {
            wanFaId = front;
        }
    }


    /**
     * 单击事件
     *
     * @author Administrator
     */
    class ZCXX_onClick implements View.OnClickListener {

        @Override
        public void onClick(View v) {
            switch (v.getId()) {
                case R.id.order_txt_continue:
                    if (AppLotteryCodeListManager.betType == AppLotteryCodeListManager.OKTOBACK) {
                        finish();
                        return;
                    }
                    if (ContinueBuy.jiXu(getContext(), getLotteryId())) {
                        finish();
                    }
                    break;
                case R.id.xiangxi_jczqsp_tv:
                    Intent intent = new Intent(OldFootballOrderDetailActivity.this, JCZQ_SPActivity.class);
                    intent.putExtra(IntentParamUtils.BETDETAILID, id);
                    startActivity(intent);
                    break;
                default:
                    break;
            }

        }

    }

    protected void perseOrder(StringResultBean resultBean) {
        info = JSON.parseObject(resultBean.getData(), ZCOrderInfo.class);
    }

    protected View addContent() {

        return RaceFactory.getRaceView(getLotteryId()).getRaceView(getContext(), getContent(), null, getPrize());
    }

    protected View addPrize() {

        return null;
    }


    @Override
    public void onRightClick() {
        lowMoney = orderMoney - (int) leftMoney;
        Intent intent = new Intent(getContext(), RechargeActivity.class);
        intent.putExtra(IntentParamUtils.ORDER_ID, id);
        intent.putExtra(IntentParamUtils.lowMoney, lowMoney);
        startActivityForResult(intent, IntentParamUtils.LOWMONEY_TO_RECHARGE_OK);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == IntentParamUtils.LOWMONEY_TO_RECHARGE_OK) {  // 支付完返回 刷新订单
            getOrderInfo();
        }
    }
}
